package Test

import (
	"errors"
	"fmt"
	MgoPool "gitee.com/tym_hmm/mgo-pool"
	"gitee.com/tym_hmm/mgo-pool/Test/Field"
	"gopkg.in/mgo.v2"
)

type testModel struct {
	MgoPool.BaseMgoManyModel
	Field.FieldTest
}

func NewTestModel() *testModel {
	return &testModel{}
}

func (this *testModel) Build() {
	this.SetBuildName("default")
}

func (this *testModel) CreateRow(data *Field.FieldTest) error {
	this.Build()
	collection := this.GetCollection()
	err := this.GetSession(func(session *mgo.Session, db *mgo.Database) error {
		c := db.C(collection)
		err := c.Insert(&data)
		if err != nil {
			fmt.Printf("err => %+v\n", err)
			return err
		}
		return nil
	})
	if err != nil {
		fmt.Println("err", err)
		return err
	}
	return nil
}

func (this *testModel) CreateRowSession(data *Field.FieldTest) error {
	this.Build()
	collection := this.GetCollection()
	session, db, errMgo := this.GetSessionOnly()
	if errMgo != nil {
		return errors.New(errMgo.Error())
	}
	defer session.Close()
	c := db.C(collection)
	err := c.Insert(&data)
	if err != nil {
		return err
	}
	return nil
}

func (this *testModel) GetS() {
	this.Build()
	_ = this.GetCollection()
	s, _, e := this.GetSessionOnly()
	if e != nil {
		fmt.Printf("xxx %+v\n", e)
		return
	}
	defer s.Close()
}
